/**
 * 自定义数组扩容规则，当已存储元素数量达到总容量的 80%时，扩容 1.5 倍。 例如，总容量是 10，当输入第 8 个元素时，数组进行扩容，容量从 10 变 15。
 * @author cyt
 * @date 2020/6/6
 */
public class CustomizedArray {

    private static final int INITCAPACITY = 10;

    private int[] customizedArray;

    private int capacity = 0;

    public CustomizedArray(){
        this.capacity = INITCAPACITY;
        customizedArray = new int[this.capacity];
    }
    //自定义的扩容机制
    public void capacityExtension(){
        //扩容1.5倍
        this.capacity = (int)(this.capacity * 1.5);
        int[] copy = new int[this.capacity];
        //将原来的array中的值复制到扩容后的array中
        System.arraycopy(this.customizedArray, 0, copy, 0, this.customizedArray.length);
        this.customizedArray = copy;
    }
    //数组元素的赋值
    public Integer valueAssignment(int value, int index){
        this.customizedArray[index] = value;

        //若赋值的下标大于容量的80%则扩容
        if(index + 1 >= this.capacity * 0.8){
            capacityExtension();
        }

        return value;
    }
    //获取数组指定下标的值
    public Integer getValue(int index){
        return this.customizedArray[index];
    }

    public Integer length(){
        return this.customizedArray.length;
    }


    //测试，当赋值的下标大于等于数组的容量的80%时，会自动扩容
    public static void main(String[] args){
        CustomizedArray arr = new CustomizedArray();

        System.out.println(arr.length());

        arr.valueAssignment(10, 7);

        System.out.println(arr.length());

        arr.valueAssignment(20,13);

        System.out.println(arr.length());

    }
}
